package cn.ryh.kafka.code.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;

/**
 * 同步发送流程
 *
 * @author Raoyh
 * @Description
 * @create 2022-07-26 9:22
 */
public class CustomProducerSync {
    public static void main(String[] args) {
        // 1、创建配置对象
        Properties properties = new Properties();
        // 2、给 kafka 配置对象添加配置信息：bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "119.3.50.65:8092");
        // 3、配置 key,value 序列化（必须）
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // 4、创建 kafka 生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        // 5、调用 send 方法,发送消息
        IntStream.range(0, 10).forEach((i) -> {
            // 同步发送
            try {
                kafkaProducer.send(new ProducerRecord<>("first", "kafkaSync" + i)).get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
        // 6、关闭资源
        kafkaProducer.close();
    }
}
